<?php

namespace common\models;

use Yii;
use common\models\WebsocketSever2user;

/**
 * This is the model class for table "websocket_sever".
 *
 * @property int $id ID
 * @property string $address 服务器地址： ip地址:port
 * @property int $toplimit 服务器上限人数
 * @property int $usernum 用户数量
 * @property string $addtime 添加时间
 */
class WebsocketSever extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'websocket_sever';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['address', 'addtime'], 'required'],
            [['toplimit', 'usernum', 'addtime'], 'integer'],
            [['address'], 'string', 'max' => 25],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'address' => '服务器地址： ip地址:port',
            'toplimit' => '服务器上限人数',
            'usernum' => '用户数量',
            'addtime' => '添加时间',
        ];
    }
    
    public static function distributeServer($userid){
        //判断是否存在已经分配的服务器
        $server_exist = WebsocketSever2user::checkExist($userid);
        
        //不存在时，分配一个websocket服务器给用户
        if(!$server_exist){
            //获取一个服务器
            $server = self::getAnAvailableServer();
            if(!empty($server)){
                //分配服务器
                $distributeModel = new WebsocketSever2user();
                $distributeModel->userid = $userid;
                $distributeModel->serverid = $server['id'];
                $distributeModel->server_addr = $server['address'];
                $distributeModel->addtime = time();
                if($distributeModel->save()){
                    //更新被分配的服务器的用户数量
                    self::UsernumAutoIncrement($server['id']);
                    $return = $server['address'];
                }else{
                    var_dump($distributeModel->errors);
                    exit;
                }
            }
            else{
                //服务器已满
                $return = "";
            }
            return $return;
        }
    }
    
    //获取一个可用的服务器
    public static function getAnAvailableServer(){
        $sql = "select * from websocket_sever where toplimit>usernum order by id asc";
        $command = \Yii::$app->db->createCommand($sql);
        return $command->queryOne();
    }
    
    //用户数量自增
    public static function UsernumAutoIncrement($serverid){
        $sql = "update websocket_sever set usernum=usernum+1  where id=$serverid";
        $command = \Yii::$app->db->createCommand($sql);
        return $command->execute();
    }
}
